package com.yc.bbs.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bbs.entity.Result;
import com.yc.bbs.entity.TblUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Loginzinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------------------------" + request.getServletPath());
        HttpSession session = request.getSession();
        if(session.getAttribute("myinfo") == null){
            if(request.getHeader("Accept").startsWith("applicatioin/json")){
                Result result = new Result(0,"未登录",null);
                String json = new ObjectMapper().writeValueAsString(result);
                response.getWriter().append(json);
            } else {
                session.setAttribute("RequestURI",request.getRequestURI() + "?" + request.getQueryString());
                // TODO 打开页面是提示用户必须先登录 cause=1 表示未登录
                String contextPath = request.getServletContext().getContextPath();
                response.sendRedirect(contextPath+"/login.html?cause=1");
            }
            return false;
        }

        if (request.getServletPath().startsWith("/back")) {
            TblUser myinfo = (TblUser) session.getAttribute("myinfo");
            if ("admin".equals(myinfo.getRole()) == false) {
                if(request.getHeader("Accept").startsWith("applicatioin/json")){
                    Result result = new Result(0,"权限不足",null);
                    String json = new ObjectMapper().writeValueAsString(result);
                    response.getWriter().append(json);
                } else {
                    session.setAttribute("RequestURI",request.getRequestURI() + "?" + request.getQueryString());
                    // TODO 打开页面是提示用户必须先登录 cause=2 表示权限不足
                    String contextPath = request.getServletContext().getContextPath();
                    response.sendRedirect(contextPath+"/login.html?cause=2");
                }
                return false;
            }
        }
        return true;
    }
}
